/*
习题二
fp方法应用
*/

const fp = require('lodash/fp');
const cars = [
    {name: 'Ferrari FF', horsepower: 660, dollar_value: 700000, in_stock: true},
    {name: 'Spyker C12 Zagato', horsepower: 650, dollar_value: 648000, in_stock: false},
    {name: 'Jaguar XKR-S', horsepower: 550, dollar_value: 13200, in_stock: false},
    {name: 'Audi R8', horsepower: 525, dollar_value: 114200, in_stock: false},
    {name: 'Aston Martin One-77', horsepower: 660, dollar_value: 1850000, in_stock: true},
    {name: 'Pagani Huayra', horsepower: 700, dollar_value: 120000, in_stock: false},
];


/*
练习一，使用函数组合fp.flowRight()重新实现
思路：将函数拆分成获取数据函数和获取属性函数， 再用fp.flowRight()组合起来
*/
/*获取最后一条数据*/
const lastCar = cars => fp.last(cars);

/*获取最后一条数据的 in_stock 属性值*/
const inStock = last_car => fp.prop('in_stock', last_car);

const isLastInStock = fp.flowRight(inStock, lastCar);
console.log('isLastInStock', isLastInStock(cars));

/*
练习二，使用flowRight()、fp.props()和fp.first()获取第一个car的name
思路与练习一一致
*/
const firstCar = cars => fp.first(cars);
const carName = first_car =>  fp.prop('name', first_car);
const isFirstName = fp.flowRight(carName, firstCar);
console.log('isFirstName', isFirstName(cars));

/*
练习三，使用_average重构averageDollarValue
思路：先获取价格数组， 在调用_average函数
*/
const _average = xs => fp.reduce(fp.add, 0 , xs) / xs.length;

/*调用fp.map()方法遍历数据，通过fp.prop()获取dollar_value值，生成价格数组*/
const averageDollarValue = fp.flowRight(_average, fp.map(fp.props('dollar_value')));
console.log(averageDollarValue(cars));

/*
练习四：把数组中参数转换成小写下划线格式
思路， 遍历数组，把更改的值替换成小写下划线格式
*/

const a = ['Name Dark', 'App view']
const _underscore = fp.replace(/\W+/g, '_');
/*函数组合，合成小写下换线格式*/
const changeName = fp.flowRight(_underscore, fp.toLower);
/*遍历数组， 替换name*/
const sanitizeNames = fp.map(car => car.name = changeName(car.name));
sanitizeNames(cars);
console.log(cars);

